﻿using System;
using System.Collections.ObjectModel;
using System.ComponentModel;
using GpgApi;

namespace WgpgCore
{
    public sealed class TaskManager : INotifyPropertyChanged
    {
        public static readonly TaskManager Instance = new TaskManager();

        public event PropertyChangedEventHandler PropertyChanged;

        private readonly ObservableCollection<Task> _tasks;
        public ExternalReadOnlyObservableCollection<Task> Tasks { get; private set; }

        private Boolean _isRunning = false;
        public Boolean IsRunning
        {
            get { return _isRunning; }
            private set
            {
                if (_isRunning == value)
                    return;

                _isRunning = value;
                if (PropertyChanged != null)
                    PropertyChanged(this, new PropertyChangedEventArgs("IsRunning"));
            }
        }

        private TaskManager()
        {
            _tasks = new ObservableCollection<Task>();
            Tasks = new ExternalReadOnlyObservableCollection<Task>(_tasks);
        }

        public void Add(GpgInterface gpg, String name, String description = null)
        {
            foreach (Task task in _tasks)
                if (task.IsSame(gpg))
                    return;

            Task newtask = new Task(gpg, name, description);
            newtask.PropertyChanged += delegate(Object sender, PropertyChangedEventArgs e) { UpdateProgressBar(); };
            _tasks.Insert(0, newtask);

            UpdateProgressBar();
        }

        public void CleanList()
        {
            Int32 i = 0;
            while (i < _tasks.Count)
            {
                Task task = _tasks[i];
                if (task.Status == TaskStatus.Error || task.Status == TaskStatus.Success)
                    _tasks.RemoveAt(i);
                else
                    i++;
            }
        }

        private void UpdateProgressBar()
        {
            Boolean running = false;
            foreach (Task task in _tasks)
            {
                if (task.Status == TaskStatus.Running)
                {
                    running = true;
                    break;
                }
            }

            IsRunning = running;
        }
    }
}
